const { EvaluationRecord, GameRecord, DailyRecord } = require('../dao/model');
const userServices = require('./userServices');

class EvaluationServices {
  // 语音评测
  async evaluateAudio(userId, text, audioFile) {
    try {
      // 模拟语音评测算法
      const score = Math.floor(Math.random() * 30) + 70; // 70-100分
      const accuracy = Math.floor(Math.random() * 20) + 80; // 80-100
      const fluency = Math.floor(Math.random() * 25) + 75; // 75-100
      const completeness = Math.floor(Math.random() * 15) + 85; // 85-100

      let level = '优秀';
      if (score < 85) level = '良好';
      if (score < 75) level = '一般';
      if (score < 65) level = '需要改进';

      const suggestions = [];
      if (accuracy < 85) suggestions.push('注意发音准确性，可以多听标准发音');
      if (fluency < 80) suggestions.push('语调可以更自然一些，注意语音的连贯性');
      if (completeness < 90) suggestions.push('注意语句的完整性和情感表达');
      if (suggestions.length === 0) suggestions.push('发音清晰准确，继续保持！');

      // 保存评测记录
      const evaluationRecord = await EvaluationRecord.create({
        user_id: userId,
        text,
        audio_url: audioFile ? `/uploads/audio/${audioFile.filename}` : null,
        score,
        accuracy,
        fluency,
        completeness,
        level,
        suggestions,
        duration: Math.floor(Math.random() * 60) + 30, // 模拟录音时长
        evaluation_type: 'free'
      });

      // 增加学习时长和积分
      await userServices.addStudyTime(userId, 300); // 5分钟学习时长
      
      // 根据分数给予积分奖励
      let bonusPoints = 0;
      if (score >= 90) bonusPoints = 10;
      else if (score >= 80) bonusPoints = 5;
      else if (score >= 70) bonusPoints = 2;
      
      if (bonusPoints > 0) {
        await userServices.addPoints(userId, bonusPoints);
      }

      return {
        id: evaluationRecord.id,
        score,
        level,
        accuracy,
        fluency,
        completeness,
        suggestions,
        bonusPoints
      };
    } catch (error) {
      throw new Error(`语音评测失败: ${error.message}`);
    }
  }

  // 获取评测历史
  async getEvaluationHistory(userId, page = 1, limit = 10) {
    try {
      const offset = (page - 1) * limit;
      
      const { count, rows } = await EvaluationRecord.findAndCountAll({
        where: { user_id: userId },
        order: [['created_at', 'DESC']],
        limit,
        offset
      });

      // 计算统计数据
      const statistics = {
        totalEvaluations: count,
        averageScore: count > 0 ? 
          Math.round(rows.reduce((sum, record) => sum + record.score, 0) / count * 10) / 10 : 0,
        bestScore: count > 0 ? Math.max(...rows.map(record => record.score)) : 0,
        recentImprovement: this.calculateImprovement(rows)
      };

      return {
        list: rows,
        total: count,
        page,
        limit,
        statistics
      };
    } catch (error) {
      throw new Error(`获取评测历史失败: ${error.message}`);
    }
  }

  // 获取评测详情
  async getEvaluationDetail(userId, recordId) {
    try {
      const record = await EvaluationRecord.findOne({
        where: { 
          id: recordId,
          user_id: userId 
        }
      });

      if (!record) {
        throw new Error('评测记录不存在');
      }

      return record;
    } catch (error) {
      throw new Error(`获取评测详情失败: ${error.message}`);
    }
  }

  // 游戏评测
  async evaluateGame(userId, contentId, audioFile) {
    try {
      // 模拟游戏内容
      const gameContents = [
        { id: 1, text: '苹果', pinyin: 'píng guǒ' },
        { id: 2, text: '香蕉', pinyin: 'xiāng jiāo' },
        { id: 3, text: '汽车', pinyin: 'qì chē' },
        { id: 4, text: '房子', pinyin: 'fáng zi' },
        { id: 5, text: '蝴蝶', pinyin: 'hú dié' }
      ];

      const content = gameContents.find(c => c.id === parseInt(contentId));
      if (!content) {
        throw new Error('游戏内容不存在');
      }

      // 模拟评测结果
      const similarity = Math.floor(Math.random() * 30) + 70; // 70-100
      const score = Math.floor(Math.random() * 30) + 70; // 70-100

      let level = '优秀';
      if (score < 85) level = '良好';
      if (score < 75) level = '一般';
      if (score < 65) level = '需要改进';

      const suggestions = [];
      if (similarity < 80) suggestions.push('发音需要更加准确');
      if (score < 80) suggestions.push('可以多练习几次');
      if (suggestions.length === 0) suggestions.push('发音清晰，继续保持');

      // 保存游戏记录
      const gameRecord = await GameRecord.create({
        user_id: userId,
        content_id: contentId,
        content_title: content.text,
        user_pronunciation: content.text, // 简化处理
        standard_pronunciation: `${content.text} (${content.pinyin})`,
        similarity,
        score,
        level,
        suggestions,
        audio_url: audioFile ? `/uploads/audio/${audioFile.filename}` : null
      });

      // 增加学习时长和积分
      await userServices.addStudyTime(userId, 120); // 2分钟学习时长
      
      // 根据分数给予积分奖励
      let bonusPoints = 0;
      if (score >= 90) bonusPoints = 5;
      else if (score >= 80) bonusPoints = 3;
      else if (score >= 70) bonusPoints = 1;
      
      if (bonusPoints > 0) {
        await userServices.addPoints(userId, bonusPoints);
      }

      return {
        id: gameRecord.id,
        contentTitle: content.text,
        userPronunciation: content.text,
        standardPronunciation: `${content.text} (${content.pinyin})`,
        similarity,
        score,
        level,
        suggestions,
        bonusPoints
      };
    } catch (error) {
      throw new Error(`游戏评测失败: ${error.message}`);
    }
  }

  // 每日朗读评测
  async evaluateDaily(userId, sentenceId, videoFile) {
    try {
      // 模拟每日句子
      const dailySentences = [
        { id: 1, text: '学而时习之，不亦说乎。', pinyin: 'xué ér shí xí zhī, bù yì yuè hū.' },
        { id: 2, text: '温故而知新，可以为师矣。', pinyin: 'wēn gù ér zhī xīn, kě yǐ wéi shī yǐ.' },
        { id: 3, text: '知之者不如好之者，好之者不如乐之者。', pinyin: 'zhī zhī zhě bù rú hào zhī zhě, hào zhī zhě bù rú lè zhī zhě.' }
      ];

      const sentence = dailySentences.find(s => s.id === parseInt(sentenceId));
      if (!sentence) {
        throw new Error('句子不存在');
      }

      // 检查今日是否已经朗读过
      const today = new Date().toISOString().split('T')[0];
      const existingRecord = await DailyRecord.findOne({
        where: {
          user_id: userId,
          date: today
        }
      });

      if (existingRecord) {
        throw new Error('今日已完成朗读');
      }

      // 模拟评测结果
      const score = Math.floor(Math.random() * 30) + 70; // 70-100分
      const accuracy = Math.floor(Math.random() * 20) + 80; // 80-100
      const fluency = Math.floor(Math.random() * 25) + 75; // 75-100
      const completeness = Math.floor(Math.random() * 15) + 85; // 85-100

      let level = '优秀';
      if (score < 85) level = '良好';
      if (score < 75) level = '一般';
      if (score < 65) level = '需要改进';

      const suggestions = [];
      if (accuracy < 85) suggestions.push('注意发音准确性');
      if (fluency < 80) suggestions.push('语调可以更自然一些');
      if (completeness < 90) suggestions.push('注意情感表达');
      if (suggestions.length === 0) suggestions.push('语调自然，发音准确');

      // 保存每日记录
      const dailyRecord = await DailyRecord.create({
        user_id: userId,
        sentence_id: sentenceId,
        sentence: sentence.text,
        date: today,
        score,
        level,
        accuracy,
        fluency,
        completeness,
        video_url: videoFile ? `/uploads/video/${videoFile.filename}` : null,
        suggestions
      });

      // 增加学习时长和积分
      await userServices.addStudyTime(userId, 180); // 3分钟学习时长
      
      // 每日朗读额外奖励
      let bonusPoints = 10; // 基础奖励
      if (score >= 90) bonusPoints += 5;
      else if (score >= 80) bonusPoints += 3;
      
      await userServices.addPoints(userId, bonusPoints);

      return {
        id: dailyRecord.id,
        sentence: sentence.text,
        score,
        level,
        accuracy,
        fluency,
        completeness,
        suggestions,
        bonusPoints
      };
    } catch (error) {
      throw new Error(`每日朗读评测失败: ${error.message}`);
    }
  }

  // 计算改进趋势
  calculateImprovement(records) {
    if (records.length < 2) return 0;
    
    const recent = records.slice(0, 5); // 最近5次
    const previous = records.slice(5, 10); // 之前5次
    
    if (previous.length === 0) return 0;
    
    const recentAvg = recent.reduce((sum, r) => sum + r.score, 0) / recent.length;
    const previousAvg = previous.reduce((sum, r) => sum + r.score, 0) / previous.length;
    
    return Math.round((recentAvg - previousAvg) * 10) / 10;
  }

  // 获取用户学习统计
  async getUserLearningStats(userId) {
    try {
      const evaluationCount = await EvaluationRecord.count({
        where: { user_id: userId }
      });

      const gameCount = await GameRecord.count({
        where: { user_id: userId }
      });

      const dailyCount = await DailyRecord.count({
        where: { user_id: userId }
      });

      // 计算平均分数
      const evaluationRecords = await EvaluationRecord.findAll({
        where: { user_id: userId },
        attributes: ['score']
      });

      const gameRecords = await GameRecord.findAll({
        where: { user_id: userId },
        attributes: ['score']
      });

      const dailyRecords = await DailyRecord.findAll({
        where: { user_id: userId },
        attributes: ['score']
      });

      const allScores = [
        ...evaluationRecords.map(r => r.score),
        ...gameRecords.map(r => r.score),
        ...dailyRecords.map(r => r.score)
      ];

      const averageScore = allScores.length > 0 ? 
        Math.round(allScores.reduce((sum, score) => sum + score, 0) / allScores.length * 10) / 10 : 0;

      return {
        totalPractices: evaluationCount + gameCount + dailyCount,
        evaluationCount,
        gameCount,
        dailyCount,
        averageScore,
        bestScore: allScores.length > 0 ? Math.max(...allScores) : 0
      };
    } catch (error) {
      throw new Error(`获取学习统计失败: ${error.message}`);
    }
  }
}

module.exports = new EvaluationServices();
